<template>
	<div>
		<el-dialog title=" " :show-close="showClose" :close-on-click-modal="false" :close-on-press-escape="false"
			:visible.sync="dialog" :modal="false" fullscreen center custom-class="custom-dialog" @close="dialogClose">
			<div class="video-wrap">
				<div class="wrap-select">
					<label>当前用户：{{ user.userName }}</label>
					<label style="margin-left: 20px;">用户组：</label>
					<el-select size="mini" collapse-tags v-model="userGroupIdList" multiple placeholder="请选择用户组"
						@change="groupChange">
						<el-option v-for="(item, index) in groupList" :key="index" :label="item.bizUserGroupName"
							:value="item.userGroupId"> </el-option>
					</el-select>
					<label style="margin-left: 20px;">排列方式：</label>
					<el-select size="mini" v-model="columnNum" placeholder="请选择排列方式">
						<el-option label="3列" :value="3"> </el-option>
						<el-option label="5列" :value="5"> </el-option>
						<el-option label="10列" :value="10"> </el-option>
					</el-select>
					<el-button type="primary" size="mini" style="margin-left: 20px;" @click="handleInvite">快速入会
					</el-button>
				</div>
				<div class="wrap-tab">
					<div class="wrap-user">
						<video id="user-avatar"></video>
					</div>
					<div class="wrap-tabitem" :class="{ 'wrap-active': tabCurrent == 0 }" @click="tabCurrent = 0">
						<i class="el-icon-turn-off"></i>
						<span>终端</span>
					</div>
				</div>
				<div class="wrap-content">
					<div v-show="tabCurrent == 0" class="dialog-list">
						<div class="mobile-card" :class="[item.disabled && 'disabled']"
							:style="{ width: 'calc(100%/' + columnNum + ' - 10px)' }" v-for="(item, index) in tableData"
							:key="index" @click.stop.prevent="handleJump(index)">
							<div class="card-title">
								<div class="card-name">{{ item.userName }}</div>
								<el-link v-if="item.userStatus === 'MEETING' && item.userType == '0'"
									type="success">终端在线</el-link>
								<el-link v-else-if="statusEnum[item.userStatus]" :type="statusEnum[item.userStatus].type">
									{{ statusEnum[item.userStatus].name }}
								</el-link>
							</div>
							<div class="card-cover" v-if="columnNum < 10"
								:style="{ backgroundImage: `url(${item.meetingImgUrl || item.userAvatarUrl})` }">
							</div>
							<div class="card-checkbox">
								<el-checkbox :class="[item.disabled && 'disabled']" v-model="item.selected">
								</el-checkbox>
							</div>
						</div>
					</div>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	createMeetingRoom,
	getUserGroup,
	listByUserGroup
} from '@/api'
import {
	mapState
} from 'vuex'
export default {
	name: 'Terminal',
	data() {
		return {
			dialog: false,
			tabCurrent: 0,
			tableData: [],
			meetingType: 0,
			total: 0,
			columnNum: 3,
			videoTrack: undefined,
			statusEnum: {
				'OFFLINE': {
					name: '离线',
					type: 'info',
				},
				'ONLINE': {
					name: '在线',
					type: 'success'
				},
				'MEETING': {
					name: '会议中',
					type: 'danger',
				}
			},
			groupList: [],
			userGroupIdList: [],
			timer: null,
			showClose: true
		}
	},
	computed: {
		...mapState(['websock', 'user']),
		targetUserIdList() {
			let arr = this.tableData.filter(item => item.selected)
			return arr.map(item => item.userId)
		}
	},
	activated() {
		this.userGroupIdList.length && this.getList()
		this.userGroupIdList.length && this.startPolling()
	},
	deactivated() {
		this.closeTimer()
	},
	methods: {
		open() {
			this.dialog = true
			this.closeTimer()
			this.getGroupList().then(() => {
				this.userGroupIdList.length && this.getList()
				this.userGroupIdList.length && this.startPolling()
			})
			this.$nextTick(() => {
				this.getMedia()
			})
		},
		startPolling() {
			this.timer = setInterval(() => {
				this.getList()
			}, 10000);
		},
		getList() {
			listByUserGroup({
				userGroupIdList: this.userGroupIdList
			}).then(res => {
				res.data.forEach(item => {
					if (item.userStatus == 'OFFLINE') {
						item.selected = false
						item.disabled = true
					} else {
						let isSelf = item.userId == this.user.id
						let isMeeting = item.userStatus == 'MEETING'
						item.selected = isSelf || this.targetUserIdList.includes(item.userId)
						item.disabled = isMeeting || isSelf
						if (item.userType == '0' && isMeeting) {
							item.disabled = false
						}
					}

				})
				this.tableData = res.data
			})
		},
		groupChange() {
			this.closeTimer()
			this.getList()
			this.startPolling()
		},
		async handleInvite() {
			if (!this.targetUserIdList.length) {
				return this.$message.warning('请选择邀请人员!')
			}

			let code, meetingRoomName, sessionId;
			let item = this.tableData.find(item => item.selected && item.userType == '0')
			if (item) {
				code = item.meetingRoomCode
				meetingRoomName = item.meetingRoomName
				sessionId = item.sessionId
			} else {
				meetingRoomName = new Date().getTime().toString().substring(3, 15)
				await createMeetingRoom({
					meetingRoomName
				}).then(res => {
					code = res.data.code
					sessionId = res.data.sessionId
				})
			}

			const data = {
				event: 'userNotification',
				targetUserIdList: this.targetUserIdList,
				data: {
					code,
					sessionId,
					meetingRoomName,
					userName: this.user.userName,
				},
				userId: this.user.id
			}
			this.websock.send(JSON.stringify(data))
			this.$router.push({
				path: "/room",
				query: {
					code,
					sessionId
				}
			})
		},
		async getGroupList() {
			await getUserGroup().then(res => {
				this.groupList = res.data
				if (this.groupList.length) {
					this.userGroupIdList = this.groupList.map(item => item.userGroupId)
				}
			})
		},
		getDisabled(item) {
			if (item.disabled) return true
			let hasTerm = this.tableData.some(item => item.selected && item.userType == '0')
			if (item.userType == '0' && !item.selected && hasTerm) {
				this.$message.info('已存在终端类型用户！')
				return true
			}
			let bool = this.targetUserIdList.length == 9 && !item.selected
			bool && this.$message.info('已达到最大邀请人数')
			return bool
		},
		// 进入会议室
		handleJump(index) {
			let item = this.tableData[index]
			if (this.getDisabled(item)) return
			item.selected = !item.selected
		},
		// 终端tab点击
		dialogClose() {
			this.videoTrack && this.videoTrack.stop()
			this.closeTimer()
			this.dialog = false
		},
		closeTimer() {
			this.timer && clearInterval(this.timer)
			this.timer = null
		},
		getMedia() {
			let constraints = {
				video: true,
				audio: false,
			};
			//获得video摄像头区域
			let video = document.getElementById("user-avatar");
			try {
				navigator.mediaDevices.getUserMedia(constraints)
					.then((stream) => {
						this.videoTrack = stream.getTracks()[0]
						video.srcObject = stream
						video.play()
					})
			} catch (e) {
				//TODO handle the exception
			}

		}
	}
}
</script>

<style lang="scss" scoped>
.custom-dialog {
	background: #222 !important;
}

::v-deep .el-dialog {
	background: #222 !important;
}

.wrap-select {
	position: absolute;
	top: -40px;
	left: 120px;
	display: flex;
	align-items: center;
	color: #fff;

	::v-deep {

		.el-select-dropdown,
		.el-select {
			filter: invert(85%) hue-rotate(180deg);
		}

		.el-select__tags {
			max-width: none !important;
		}
	}
}

.video-wrap {
	position: relative;
	display: flex;
	height: 83vh;
	margin-top: 10px;
	padding-top: 10px;

	.wrap-tab {
		width: 96px;
		background-color: #555;
		height: 100%;
		border-radius: 10px;
	}

	.wrap-content {
		flex: 1;
		width: 0;
		height: 100%;
		margin-left: 20px;
		background-color: #8c8c8c;

		::v-deep {
			.el-table {
				filter: invert(85%) hue-rotate(180deg);
			}
		}
	}

	.wrap-user {
		height: 80px;
		border-radius: 10px 10px 0 0;

		video {
			border-radius: inherit;
			width: 100%;
			height: 100%;
		}
	}

	.wrap-tabitem {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #fff;
		padding: 10px 0;

		i {
			font-size: 24px;
		}

		span {
			margin-top: 8px;
		}
	}

	.wrap-active {
		background-color: #ec5353;
	}
}

.dialog-list {
	display: flex;
	flex-wrap: wrap;
}

.mobile-card:hover {
	opacity: 0.7;
}

.mobile-card {
	position: relative;
	margin: 0 10px 20px 0;
	width: 100%;
	min-height: 72px;
	background: #FFFFFF;
	box-shadow: 0px 4px 10px 0px rgba(119, 119, 119, 0.12);
	border-radius: 8px;
	transition: all .3s;

	.card-title {
		position: absolute;
		top: 10px;
		left: 10px;
		color: #fff;
		z-index: 99;
	}

	.card-name {
		color: #000;
	}

	.card-cover {
		position: relative;
		width: 100%;
		padding-bottom: 50%;
		border-radius: 4px;
		background-repeat: no-repeat;
		background-size: cover;
		background-position: center;
		border-radius: 8px;

		i {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			font-size: 48px;
			color: #fff;
		}
	}

	.card-checkbox {
		position: absolute;
		top: 2px;
		right: 5px;
	}
}

.disabled {
	pointer-events: auto;
	cursor: not-allowed;
}
</style>
